<template>
  <div>
    <h1>抽奖活动列表</h1>
    <!-- 条件搜索 -->
    <div style="margin-top: 10px">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="活动名称">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入活动名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadActiveList">查询</el-button>
          <el-button type="primary" @click="toAddActive">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格数据 -->
    <div style="margin-top: 10px">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="activeId" label="活动ID" width="70" />
        <el-table-column prop="activeName" label="活动名称" width="100" />
        <el-table-column prop="beginTime" label="开始时间" width="160" />
        <el-table-column prop="endTime" label="截止时间" width="160" />
        <el-table-column prop="joinUser" label="参与用户" width="80" />
        <el-table-column prop="freeTimes" label="免费抽奖次数" width="120" />
        <el-table-column prop="winUser" label="中奖名单" width="100" />
        <el-table-column prop="winList" label="中奖记录" width="100" />
        <el-table-column prop="statusName" label="活动状态" width="100" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="info"
              @click="onUpdateActive(scope.row)"
              size="small"
              >编辑</el-button
            >
            <el-button
              type="danger"
              @click="onDeleteActive(scope.row)"
              size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 10px">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 修改 -->

    <div>
      <el-dialog v-model="dialogFormVisible" title="添加规则" width="1100">
        <el-form
          ref="ruleFormRef"
          style="max-width: 1200px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
        >
          <el-form-item label="活动名称" prop="name" style="width: 400px">
            <el-input
              v-model="ruleForm.activeName"
              placeholder="请输入活动名称"
            />
          </el-form-item>
          <el-form-item label="活动时间" required style="width: 500px">
            <el-date-picker
              v-model="ruleForm.activeTime"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD ddd"
              time-format="A hh:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="参与用户" prop="resource" style="width: 400px">
            <el-radio-group v-model="ruleForm.userFlag">
              <el-radio
                v-for="item in userFlagList"
                :value="item.dictValue"
                :key="item.dectId"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="活动免费抽奖次数"
            prop="name"
            style="width: 400px"
          >
            <el-input
              v-model="ruleForm.freeTimes"
              placeholder="请输入抽奖次数"
            />
          </el-form-item>
          <el-form-item label="规则选择" prop="name" style="width: 1000px">
            <el-table :data="ruleList" stripe style="width: 100%">
              <el-table-column prop="ruleId" label="序号" width="60" />
              <el-table-column prop="ruleImage" label="图片" width="80">
                <template #default="scope">
                  <el-image
                    v-if="scope.row.ruleImage"
                    :src="scope.row.ruleImage"
                    style="width: 50px; height: 50px"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="ruleName" label="名称" width="100" />
              <el-table-column prop="winProd" label="奖品" width="100" />
              <el-table-column prop="winImage" label="中奖弹窗图片" width="110">
                <template #default="scope">
                  <el-image
                    v-if="scope.row.winImage"
                    :src="scope.row.winImage"
                    style="width: 50px; height: 50px"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="prodNum" label="数量" width="80" />
              <el-table-column prop="winChance" label="奖品概率" width="80" />
              <el-table-column label="操作" />
            </el-table>
            <div>
              <el-button type="primary" size="small" @click="onAddRule"
                >添加规则</el-button
              >
            </div>
          </el-form-item>
          <el-form-item label="中奖名单" prop="delivery" style="width: 400px">
            <el-switch
              v-model="ruleForm.winFlag"
              active-text="公开"
              inactive-text="隐藏"
              :active-value="0"
              :inactive-value="1"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
            />
          </el-form-item>
          <el-form-item label="中奖记录" prop="delivery" style="width: 400px">
            <el-switch
              v-model="ruleForm.winRecord"
              active-text="公开"
              inactive-text="隐藏"
              :active-value="0"
              :inactive-value="1"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
            />
          </el-form-item>
          <el-form-item label="活动状态" prop="delivery" style="width: 400px">
            <el-switch
              v-model="ruleForm.activeStatus"
              :active-value="0"
              :inactive-value="1"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
            />
          </el-form-item>
          <el-form-item label="活动规则" prop="delivery" style="width: 700px">
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 500px; overflow-y: hidden"
                v-model="ruleForm.activeContent"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              完成
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">返回</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!-- 添加规则 -->
    <div>
      <el-dialog v-model="FormVisible" title="添加规则" width="500">
        <el-form :model="form">
          <el-form-item label="名称" :label-width="formLabelWidth">
            <el-input v-model="form.ruleName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="图片" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/prod/type/uploadImage"
              :show-file-list="false"
              :on-success="handleRuleImageSuccess"
              :headers="headers"
            >
              <img v-if="ruleImage" :src="ruleImage" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="奖品" :label-width="formLabelWidth">
            <el-input v-model="form.winProd" autocomplete="off" />
          </el-form-item>
          <el-form-item label="中奖弹窗图片" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/prod/type/uploadImage"
              :show-file-list="false"
              :on-success="handleWinImageSuccess"
              :headers="headers"
            >
              <img v-if="winImage" :src="winImage" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="数量" :label-width="formLabelWidth">
            <el-input v-model="form.prodNum" autocomplete="off" />
          </el-form-item>
          <el-form-item label="奖品概率" :label-width="formLabelWidth">
            <el-input v-model="form.winChance" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="onSumbitAddRule">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { reactive } from "vue";
import {
  getActiveList,
  updateActive,
  deleteActive,
  getActiveRuleList,
  getDictList,
} from "../api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

const tableData = ref([]);
const total = ref(0);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: "",
});

const mode = "default";

interface RuleForm {
  activeContent: string;
  activeName: string;
  activeStatus: number;
  activeTime: [];
  beginTime: string;
  endTime: string;
  freeTimes: number;
  userFlag: number;
  winFlag: number;
  winRecord: number;
  ruleList: [];
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  activeContent: "",
  activeName: "",
  activeStatus: 0,
  activeTime: [],
  beginTime: "",
  endTime: "",
  freeTimes: 0,
  ruleList: [],
  userFlag: 0,
  winFlag: 0,
  winRecord: 0,
});

const ruleList = ref<any>([]);
const userFlagList = ref([]);
//上传图片
const ruleImage = ref("");
const winImage = ref("");
const headers = ref({
  token: sessionStorage.getItem("token") || "",
});
const handleRuleImageSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // ruleImage.value = URL.createObjectURL(uploadFile.raw!)
  ruleImage.value = response.data;
};
const handleWinImageSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // ruleImage.value = URL.createObjectURL(uploadFile.raw!)
  winImage.value = response.data;
};

//显示修改
const onUpdateActive = (row: any) => {
  console.log("onUpdateActive", row);
  Object.assign(ruleForm, row);
  // 确保activeTime是包含两个元素的数组
  if (row.beginTime && row.endTime) {
    ruleForm.activeTime = [row.beginTime, row.endTime];
  } else {
    ruleForm.activeTime = [];
  }

  const rule: any = {};
  //克隆一个对象
  Object.assign(rule, form);
  rule.ruleImage = ruleImage.value;
  rule.winImage = winImage.value;
  getActiveRuleList(row.activeId).then((res) => {
    if (res.data.code == 200) {
      ruleList.value = res.data.data;
    }
  });
  dialogFormVisible.value = true;
};

const onAddRule = () => {
  console.log("onAddRule");
  Object.assign(form, {
    prodNum: 0,
    ruleImage: "",
    ruleName: "",
    winChance: 0,
    winImage: "",
    winProd: "",
  });
  ruleImage.value = "";
  winImage.value = "";
  FormVisible.value = true;
};
const onSumbitAddRule = () => {
  console.log("onSumbitAddRule");
  const rule: any = {};
  //克隆一个对象
  Object.assign(rule, form);
  rule.ruleImage = ruleImage.value;
  rule.winImage = winImage.value;
  ruleList.value.push(rule);

  //初始化表单
  Object.assign(form, {
    prodNum: 0,
    ruleImage: "",
    ruleName: "",
    winChance: 0,
    winImage: "",
    winProd: "",
  });
  ruleImage.value = "";
  winImage.value = "";
};

const dialogFormVisible = ref(false);
const FormVisible = ref(false);
const formLabelWidth = "140px";
const form = reactive({
  prodNum: 0,
  ruleImage: "",
  ruleName: "",
  winChance: 0,
  winImage: "",
  winProd: "",
});

const rules = reactive<FormRules<RuleForm>>({
  activeName: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
});

//提交修改抽奖活动的表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      ruleForm.ruleList = ruleList.value;
      updateActive(ruleForm).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("修改成功");
          loadActiveList();
          dialogFormVisible.value = false;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  //初始化表单
  Object.assign(form, {
    prodNum: 0,
    ruleImage: "",
    ruleName: "",
    winChance: 0,
    winImage: "",
    winProd: "",
  });
  dialogFormVisible.value = false;
};

//删除抽奖活动
const onDeleteActive = (row: any) => {
  console.log("onDeleteActive", row);

  ElMessageBox.confirm("删除之后无法恢复，您确认要删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then((res) => {
      deleteActive(row.activeId).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          loadActiveList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//显示添加对话框
const toAddActive = () => {
  console.log("toAddActive");
  router.push("/home/addActive");
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadActiveList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadActiveList();
};

const loadActiveList = () => {
  getActiveList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

//富文本
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("<p>hello</p>");
// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = "<p>模拟 Ajax 异步设置内容</p>";
  }, 1500);
});
const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

onMounted(() => {
  loadActiveList();
  //获取参与用户
  getDictList(5).then((res) => {
    if (res.data.code == 200) {
      userFlagList.value = res.data.data;
    }
  });
});
</script>

<!-- 分页样式 -->
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
<!-- 条件搜索样式 -->
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
